﻿@using TD.Common.Kendo.Mvc5.Grid

@model TD.CTS.Data.Entities.Trial

@{
    var isNew = ViewBag.IsNew;
}

@*@Html.Partial("EditorTemplates/TrialVersionEditor", Model)*@

<table id="trialForm" class="td-formTable" style="width:auto;margin-bottom:20px;">
    <tr>
        <td class="td-formTable-caption" colspan="2" style="width:250px;">Код исследования</td>
        <td>
            @Html.EditorFor(model => model.Code)
        </td>
    </tr>
    @if (!isNew)
    { 
    <tr>
        <td class="td-formTable-caption" colspan="2" style="width:150px;">Версия исследования</td>
        <td>
            @(Html.Kendo().DropDownListFor(model => model.Version)
                .BindTo((System.Collections.IEnumerable)ViewBag.Versions)
                .DataTextField("Name")
                .DataValueField("Id")
            )
            @Html.Kendo().Button().Name("NewVersionButton").Content("Создать версию")
            @Html.Kendo().Button().Name("ActivateVersionButton").Content("Сделать активной")
        </td>
    </tr>
    }
    <tr id="StatusRow" style="display:none;">
        <td class="td-formTable-caption" colspan="2" style="width:250px;">Статус исследования</td>
        <td>
            @(Html.Kendo().DropDownList()
                .Name("Status")
                .BindTo((System.Collections.IEnumerable)ViewBag.Statuses)
                .DataTextField("Value")
                .DataValueField("Key")
                .Value(((int)Model.Status).ToString())
            )
        </td>
    </tr>
    <tr>
        <td class="td-formTable-caption" colspan="2">Наименование исследования</td>
        <td>
            @Html.EditorFor(model => model.Name)
        </td>
    </tr>
    <tr>
        <td class="td-formTable-caption" colspan="2">Администратор исследования</td>
        <td>
            @Html.EditorFor(model => model.AdministratorLogin, "GridForeignKey")
        </td>
    </tr>
    <tr>
        <td class="td-formTable-caption" colspan="2">Использовать RandN</td>
        <td>
            @Html.EditorFor(model => model.UseRandN)
        </td>
    </tr>
    <tr>
        <td class="td-formTable-caption" style="width:100px;">Заказ такси</td>
        <td colspan="2">
            @Html.EditorFor(model => model.TaxiBooking)
        </td>
    </tr>
    <tr>
        <td class="td-formTable-caption">Службы такси</td>
        <td colspan="2">
            @Html.EditorFor(model => model.TaxiService, "Text")
        </td>
    </tr>
    <tr>
        <td class="td-formTable-caption"></td>
        <td></td>
        <td>
            @(Html.Kendo().Button()
                .Name("SaveButton")
                .SpriteCssClass("k-icon k-update")
                .Content("Сохранить")
                .HtmlAttributes(new { style = "width:230px;" })
                .Events(e => e.Click("SaveTrial"))
            )
        </td>
    </tr>
    <tr>
        <td class="td-formTable-caption"></td>
        <td colspan="3"></td>
    </tr>
</table>

@(Html.Kendo().Grid<TD.CTS.Data.Entities.TrialCenter>()
    .Init("CentersGrid")
    .Editable()
    .HtmlAttributes(new { style = "display:" + (isNew ? "none" : "block") })
    .Columns(columns =>
    {
        columns.ButtonsCrud();
        columns.ForeignKey(e => e.HospitalId, (System.Collections.IEnumerable)ViewBag.Hospitals, "Id", "Name").Width(200).Title("Мед. учреждение");
        columns.Bound(e => e.Number).Width(200).Title("№ иссл. центра");
        columns.ForeignKey(e => e.AnatomistLogin, (System.Collections.IEnumerable)ViewBag.Users, "Login", "FullName").Width(200).Title("ФИО главного исслед.");
        columns.ForeignKey(e => e.CoordinatorLogin, (System.Collections.IEnumerable)ViewBag.Users, "Login", "FullName").Width("100%").Title("ФИО координатора").EditorTemplateName("GridNullableForeignKey");
    })
        .DataSource(dataSource => dataSource
            .Ajax()
            .PageSize(20)
            .Model(model =>
            {
                model.Id(e => e.Id);
            })
                .Read(read => read.Action("GetTrialCenters", "Trials").Data("GetTrialCode"))
            .Create(create => create.Action("AddTrialCenter", "Trials"))
            .Update(update => update.Action("UpdateTrialCenter", "Trials"))
            .Destroy(destroy => destroy.Action("DeleteTrialCenter", "Trials"))
            .Events(events => events.Error("kendo_grid_error_handler"))
         )
         .Events(events => events.Edit("OnCenterEdit").Save("OnCenterSave"))
         .AutoBind(!isNew)
)

<script>
    function GetTrialCode() {
        return { 
            TrialCode: $("#Code").val(), 
            TrialVersion: $("#Version").data("kendoDropDownList").value() 
        };
    }

    var validator = $("#trialForm").kendoValidator().data("kendoValidator");
    var isNew = @isNew.ToString().ToLower();

    $(document).ready(function () {
        kendo_grid_init($("#CentersGrid"));

        if(!isNew){
            $("#Code").attr("readonly", true);
            $("#StatusRow").css("display", "table-row");
        }
    });

    function SaveTrial() {
        if (validator.validate()) {
            $.ajax({
                type: "POST",
                url: "@Url.Action(isNew ? "AddTrial" : "UpdateTrial", "Trials")",
                data: {
                    Code: $("#Code").val(),
                    Version: isNew ? 1 : $("#Version").data("kendoDropDownList").value(),
                    Name: $("#Name").val(),
                    AdministratorLogin: $("#AdministratorLogin").val(),
                    TaxiBooking: $("#TaxiBooking").is(":checked"),
                    TaxiService: $("#TaxiService").val(),
                    Status: $("#Status").data("kendoDropDownList").value(),
                    UseRandN: $("#UseRandN").is(":checked")
                },
                success: function (result) {
                    if(isNew) {
                        window.location.replace("@Url.Action("Edit", "Trials")" + "/" + $("#Code").val());
                        return;
                    }

                    var saveNotification = $("#SaveNotification").data("kendoNotification");
                    saveNotification.show("Сохранено", "success");
                },
                error: AjaxError
            });
        }
    }

    function OnCenterSave(e){
        e.model.TrialCode = $("#Code").val();
        e.model.TrialVersion = $("#Version").data("kendoDropDownList").value();
    }

    function OnCenterEdit(e) {
        kendo_grid_onrowedit(e);
        if (e.model.isNew() == false) {
            e.container.find("#HospitalId").data("kendoDropDownList").enable(false);
        }
    }
</script>